import re
from copy import deepcopy

import requests


class RequestsManager:
    def __init__(self, selenium_manager):
        self.session = requests.Session()
        self.selenium_manager = selenium_manager
        self.cookies = self.selenium_manager.get_cookies()
        self.base_headers = self.selenium_manager.get_headers()
        self._update_session_cookies(self.cookies)

    def _update_session_cookies(self, cookies):
            self.session.cookies.update(cookies)

    def send_request(self, url, method, payload):
        headers = self.get_headers_for_url(url)

        if method.upper() == 'POST':
            response = self.session.post(url=url, json=payload, headers=headers)
        elif method.upper() == 'GET':
            response = self.session.get(url=url, headers=headers)
        else:
            raise ValueError(f"Unsupported HTTP method: {method}")
        
        return response
        

    def get_headers_for_url(self, url):
        """Return appropriate headers based on the URL endpoint.
        
        This method uses regular expressions to determine if the URL ends with
        specific patterns like '/graphql/' or '/submit/', and returns the corresponding headers.
        """
        # Check if URL matches specific patterns using a single regular expression
        if re.search(r'(/graphql|/submit|/noj-go)/?$', url):
                return self.get_graphql_headers()
        else:
            # Return default headers for HTML content
            return self.get_html_headers()

    def get_graphql_headers(self):
        """Return headers for GraphQL requests"""
        headers = deepcopy(self.base_headers)
        headers.update({
            "Content-Type": "application/json; charset=utf-8",
        })
        return headers

    def get_html_headers(self):
        """ Return default headers for HTML content"""
        headers = deepcopy(self.base_headers)
        headers.update({
            "Content-Type": "text/html; charset=utf-8",
        })
        return headers
    
    def process_response(self, response):
        content_type = response.headers.get('Content-Type', '')

        if 'application/json' in content_type:
            return self._process_json_response(response)
        elif 'text/html' in content_type:
            return self._process_html_response(response)
        else:
            return self._process_text_response(response)

    def _process_json_response(self, response):
        try:
            return response.json()
        except ValueError:
            raise ValueError("Invalid JSON response")

    def _process_html_response(self, response):
        return response.text

    def _process_text_response(self, response):
        return response.text